<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Core_ShiftController extends Zend_Controller_Action
{
    const ALL_FUTURE_SHIFTS = 0;
    const FUTURE_SHIFTS_NOT_CONFIRMED = 1;
    const FUTURE_SHIFTS_CONFIRMED = 2;
    const PREVIOUS_SHIFTS = 3;
    const ALL_SHIFTS = 4;

    private $_shiftService;
    private $_memberService;
    private $_shiftRoleService;

    public function init()
    {
        $this->_shiftService = $this->_helper->getService('Core_Service_Shift');
        $this->_memberService = $this->_helper->getService('Core_Service_Member');
        $this->_shiftRoleService = $this->_helper->getService('Core_Service_ShiftRole');

        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('replace', 'json')
                    ->addActionContext('replace', 'html')
                    ->initContext();
    }

    public function indexAction()
    {
        $this->_helper->acl()->isAllowed('action:core.shift', 'list');

        $filterContent = array(
            self::ALL_FUTURE_SHIFTS        =>    'Alle fremtidige vakter',
            self::FUTURE_SHIFTS_NOT_CONFIRMED  =>    'Fremtidige vakter med ubekreftet utkalling',
            self::FUTURE_SHIFTS_CONFIRMED    =>    'Fremtidige vakter med bekreftet utkalling',
            self::PREVIOUS_SHIFTS        =>    'Tidligere vakter',
            self::ALL_SHIFTS          =>    'Alle vakter'
        );
        $filterForm = $this->view->filterForm = $this->view->filterForm($filterContent);
        $filterForm->setAction($this->view->url(array('module' => 'core', 'controller' => 'shift'), null, true));

        $request = $this->getRequest();
        if ($request->isGet() && $this->_getParam('filter', false) && $filterForm->isValid($request->getQuery())) {
            $value = $filterForm->getValue('filter');
            switch ($value) {
                case self::ALL_FUTURE_SHIFTS:
                    $state = self::ALL_FUTURE_SHIFTS;
                    break;
                case self::FUTURE_SHIFTS_NOT_CONFIRMED:
                    $state = self::FUTURE_SHIFTS_NOT_CONFIRMED;
                    break;
                case self::FUTURE_SHIFTS_CONFIRMED:
                    $state = self::FUTURE_SHIFTS_CONFIRMED;
                    break;
                case self::PREVIOUS_SHIFTS:
                    $state = self::PREVIOUS_SHIFTS;
                    break;
                case self::ALL_SHIFTS:
                    $state = self::ALL_SHIFTS;
                    break;
            }
        }

        if (!isset($state)) {
            $state = self::ALL_FUTURE_SHIFTS;
        }

        $member_id = $this->view->authInfo()->getMemberId();
        $shifts = $this->_shiftService->fetchAllVisibleForMember($member_id, array('state' => $state), false);
        $this->view->shifts = $shifts;
    }

  public function viewAction()
  {
      $this->_helper->acl()->isAllowed('action:core.shift', 'view');

    $shift_id = $this->_getParam('id', false);
    $this->view->isAdmin = $this->_helper->acl()->isAllowed('service:shift', 'edit', false);
    $validator = new Zend_Validate_Int();
    if (!$validator->isValid($shift_id)) {
      throw new RedCross_Exception_ValidationFailed();
    }
    $shift_id = (int) $shift_id;

    $shift = $this->_shiftService->fetchByIdForViewShift($shift_id);

    $roles_info = array();
    foreach ($shift->Roles as $shift_role)
      $roles_info[] = $shift_role;
    usort($roles_info, array('RedCross_Global', 'shift_role_sort_cmp'));

    $this->view->shift = $shift;
    $this->view->shift_roles = $roles_info;
    $auth_service = $this->_helper->authenticator();
    $this->view->whoami = $auth_service->getIdentity();
  }

  public function confirmAction()
  {
        $this->_helper->acl()->isAllowed('service:shiftRole', 'confirmNotification');

    $this->_helper->viewRenderer->setNoRender(true);
    $id = $this->_getParam('id');
    $key = $this->_getParam('key');

    $id_val = new Zend_Validate_Int();
    $key_val = new Zend_Validate_Regex('/^[a-z0-9]{40}$/');
    if (!$id_val->isValid($id) || !$key_val->isValid($key))
    {
      throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
    }

    $id = (int) $id;

        $shift_role = $this->_shiftRoleService->fetch($id);
    if (!is_object($shift_role))
    {
      throw new RedCross_Exception_NotFound('Objekt med angitt id ikke funnet');
    }

    $result = false;
    if ($key === RedCross_Global::shift_role_hash($shift_role))
    {
      $result = $this->_shiftRoleService->confirmNotification($shift_role);
    }

    $this->view->flashMessage()->addMessage(
      $result ? 'Vaktutkalling bekreftet' : 'En ukjent feil oppstod',
       $result ? RedCross_View_Helper_FlashMessage::SUCCESS : RedCross_View_Helper_FlashMessage::ERROR);

        return $this->_helper->redirector('hasconfirmed', null, null, array('shift_id' => $shift_role->shift_id));
        /*
    $referer = $this->getRequest()->getHeader('Referer');
    if (!is_null($referer)) {
      $this->_helper->redirector->gotoUrl($referer);
        } else {

        }
        */
  }

    public function hasconfirmedAction()
    {
        $this->view->canListShifts = $this->_helper->acl()->isAllowed('action:core.shift', 'list', false);
        $canViewShift = $this->_helper->acl()->isAllowed('action:core.shift', 'view', false);
        $this->view->canViewShift = $canViewShift;
        if($canViewShift){
            $shiftId = $this->_getParam('shift_id');
            $this->view->shiftId = $shiftId;
        }


    }

  public function reportAction()
  {
    $shift_id = $this->_getParam('id');

    $id_val = new Zend_Validate_Int();
    if (!$id_val->isValid($shift_id)) {
      throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
    }
    $shift_id = (int) $shift_id;

        $shift = $this->_shiftService->fetchByIdJoinOnShiftReportShiftRolesRolesAndMember($shift_id);
    if (!is_object($shift)) {
      throw new RedCross_Exception_NotFound('Objekt med angitt id ikke funnet');
    }

    if (!is_null($shift->shift_report_id) && (bool) $shift->ShiftReport->approved) {
            throw new RedCross_Exception('Rapporten er godkjent og kan ikke endres');
    }

    $shiftRoles = $shift->Roles;
    $isLeader = false;
    $logged_in_member_id = $this->view->authInfo()->getMemberId();
    foreach($shiftRoles as $shiftRole)
    {
      if (!is_null($shiftRole->Member) && (int)$shiftRole->Member->id === $logged_in_member_id && (bool)$shiftRole->leader)
      {
        $isLeader = true;
        break;
      }
    }

        // Give access only to the shift leader and the administrator
    if (!$isLeader && !$this->_helper->acl()->isAllowed('service:shift', 'createReport', false))
    {
      throw new RedCross_Exception_Unauthorized('Ingen tilgang til rapport');
    }

    $reportForm = new Core_Form_Shift_Report();
    $reportForm->fillForm($shift);

        $request = $this->getRequest();
    if ($request->isPost() && $reportForm->isValid($request->getPost())) {
            $result = $this->_shiftService->submitShiftReport($reportForm->getValues(), $shift, $logged_in_member_id);
            if ($result === true) {
                $this->view->flashMessage()->addMessage('Vaktrapport sendt', RedCross_View_Helper_FlashMessage::SUCCESS);
                return $this->_helper->redirector('index');
            } else {
                $this->view->message = $this->view->renderMessage('En ukjent feil oppstod', RedCross_View_Helper_FlashMessage::ERROR);
            }
    }
    $this->view->reportForm = $reportForm;
    $this->view->shift = $shift;
  }

    public function replaceAction()
    {
        $roleId = $this->_getParam('role', false);

        $validator = new Zend_Validate_Int();
    if (!$validator->isValid($roleId)) {
      throw new RedCross_Exception_ValidationFailed('Ugyldig parameter angitt');
    }
    $roleId = (int) $roleId;

        $shiftRoleService = $this->_helper->getService('Core_Service_ShiftRole');

        $shiftRole = $shiftRoleService->fetchForMemberRoleTable($roleId);
        if (!$shiftRole || !is_object($shiftRole)) {
            throw new RedCross_Exception_NotFound();
        }

        if ($shiftRole->leader === 1) {
            throw new RedCross_Exception_Unauthorized('A shift leader is not authorized to replace another shift leader');
        }

        $shift = $shiftRole->Shift;
        $userId = $this->_helper->authenticator()->getIdentity()->member_id;

       // Is the logged in user a leader on the shift?
        $isLeader = false;
        foreach ($shift->Roles as $role) {
            if ($role->member_id == $userId && $role->leader === true) {
                $isLeader = true;
            }
        }
        if (!$isLeader) {
            throw new RedCross_Exception_Unauthorized('Only shift leaders are allowed to access this feature');
        }

        $request = $this->getRequest();
        if ($request->isPost()) {
            $values = $request->getPost();
            $memberId = $values['member_id'];

            if (!$validator->isValid($memberId)) {
          throw new RedCross_Exception_ValidationFailed();
        }

            $shiftRole->member_id = (int) $memberId;
            $shiftRole->notification_sent_time = null;
            $shiftRole->notification_confirmed_time = null;

            $result = $shiftRoleService->save($shiftRole);
            if($result && $request->isXmlHttpRequest()) {
                $this->view->first_name = $shiftRole->Member->first_name;
                $this->view->last_name = $shiftRole->Member->last_name;
                $this->view->sr_id = $shiftRole->id;
            } else if (!$result && $request->isXmlHttpRequest()) {
                throw new Exception('Something went wrong');
            } else if ($result && !$request->isXmlHttpRequest()) {
                $this->view->flashMessage()->addMessage('Oppdatering utført', RedCross_View_Helper_FlashMessage::SUCCESS);
                $this->_helper->redirector('view', null, null, array('id' => $shift->id));
            } else {
                throw new RedCross_Exception('Something went wrong');
            }
        } else {
            $options = array(
                Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PASSIVE => false,
                Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_PERMANENT_PASSIVE => false,
                Core_Gateway_Member::ELIGIBLE_OPTION_IGNORE_COURSES => false
            );

            $memberService = $this->_helper->getService('Core_Service_Member');
            $eligibleMembers = $memberService->fetchEligibleForRole($shiftRole, $options);

            $this->view->eligibleMembers = $eligibleMembers;
            $this->view->shiftRole = $shiftRole;
        }
    }
}
